package com.earthchen.core.handler;

import com.earthchen.core.exception.BaseException;
import com.earthchen.core.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author earthchen
 * @date 2018/8/31
 **/
@ControllerAdvice
public class CommonExceptionHandler {

    private Logger log = LoggerFactory.getLogger(CommonExceptionHandler.class);

    /**
     * 基类异常处理器
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public ResultVO handlerSellerException(BaseException e) {
        return ResultVO.error(e.getCode(), e.getMessage());
    }


    /**
     * 参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public ResultVO handlerBindException(BindException e) {

        log.info("[参数校验]---绑定异常");

        List<ObjectError> errors = e.getAllErrors();
        ObjectError error = errors.get(0);
        String msg = error.getDefaultMessage();
        return ResultVO.error(100, String.format("参数校验异常：%s", msg));
    }
}
